<template>
	<Table :columns="insideColumns" :data="value"></Table>
</template>

<script>
	import clonedeep from 'clonedeep';

	export default {
		name: "edit-table",
		data() {
			return {
				insideColumns: [],
				editingId: '',
				editingContent: ''
			}
		},
		props: {
			columns: {
				type: Array,
				default: () => []
			},
			value: {
				type: Array,
				default: () => []
			}
		},
		watch:{
			columns() {
				this.handleColumns();
			}
		},
		methods:{
			handleClick({row,index,column}) {
				if (this.editingId === `${column.key}_${index}`) {
					const tableData = clonedeep(this.value);
					tableData[index][column.key] = this.editingContent;
					this.$emit('input', tableData);
					this.$emit('on-edit',{row,index,column,newValue:this.editingContent});
					this.editingId = '';
					this.editingContent = '';
				}else {
					this.editingId = `${column.key}_${index}`;
				}
			},
			handleInput(newValue) {
				this.editingContent = newValue;
			},
			handleColumns() {
				this.insideColumns = this.columns.map(item => {
					if (!item.render && item.editable) {
						item.render = (h, {row, index, column}) => {
							const isEdit = this.editingId === `${column.key}_${index}`;
							return (
								<div>
									{isEdit ? <i-input value={row[column.key]} style="width:50px;" on-input={this.handleInput} > < /i-input> : <span>{row[column.key]}</span>}
									<i-button on-click = {this.handleClick.bind(this, {row, index, column})} > {isEdit? '保存' : '编辑'} </i-button>
								</div>
							)
						};
						return item;
					} else return item;
				});
			}
		},
		mounted() {
			this.handleColumns();
		}
	}
</script>

<style scoped>

</style>
